// pages/goods_detail/index.js
import { $http } from '../../request/index-api'
import regeneratorRuntime from '../../lib/runtime';
Page({

  data: {
    pics: [],
    goods_price: '',
    goods_name: '',
    goods_introduce: '',
    iscollect: false
  },
  detailList: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


  },
  async onShow () {
    const curPages = getCurrentPages();
    const { goods_id } = curPages[curPages.length - 1].options
    //初始获取详情数据
    await this._getGoodsDetailData(goods_id)
    const collect = wx.getStorageSync('collect') || [];
    const iscollectBol = collect.some((item) => {
      return item.goods_id == this.detailList.goods_id
    })
    if (iscollectBol) {
      this.setData({
        iscollect: true
      })
    }


  },
  //获取数据
  async _getGoodsDetailData (id) {
    const res = await $http({ url: '/goods/detail', data: { goods_id: id } })
    this.detailList = res
    this.setData({
      pics: this.detailList.pics,
      goods_price: this.detailList.goods_price,
      goods_name: this.detailList.goods_name,
      goods_introduce: this.detailList.goods_introduce
    })
  },
  //图片预览
  previewImg (e) {
    const urls = this.detailList.pics.map(item => item.pics_big_url)
    wx.previewImage({
      current: e.target.dataset.src,
      urls
    });
  }
  //添加到购物车
  , addGoods () {
    //先判断缓存中有没有数据
    //如果有商品，让num++
    //如果没有商品，获取当前商品并且存入进去
    const goods = wx.getStorageSync('goods') || [];
    const index = goods.findIndex((item) => item.goods_id === this.detailList.goods_id)
    if (index !== -1) {
      //这里是旧的数据，直接num++
      goods[index].num++
    } else {
      //这里是新的数据，没有找到商品第一次添加
      this.detailList.num = 1
      this.detailList.check = true
      goods.push(this.detailList)
    }
    wx.setStorageSync('goods', goods);
    wx.showToast({
      title: '购物车添加成功',
      icon: 'success'
    });
  },
  addCollect () {
    const collect = wx.getStorageSync('collect') || [];
    const index = collect.findIndex((item) => {
      return item.goods_id == this.detailList.goods_id
    })
    if (index !== -1) {
      //这里是找到了，说明存在
      collect.splice(index,1)
      this.setData({
        iscollect:false
      })
    } else {
      //假的没找到
      collect.push(this.detailList)
      this.setData({
        iscollect:true
      })
    }
    wx.setStorageSync('collect', collect);
  }
})